<template>
    <el-card>
        <div slot="header">
            <span>添加账号</span>
        </div>

        <!-- 表单 -->
        <el-form ref="form" :rules="rules" :model="form" label-width="100px">
            <!-- 账号 -->
            <el-form-item label="账号" prop="account">
                <el-input v-model="form.account"></el-input>
            </el-form-item>

            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" type="password" show-password></el-input>
            </el-form-item>

            <!-- 用户组 -->
            <el-form-item label="用户组" prop="userGroup">
                <el-select v-model="form.userGroup" placeholder="请选择用户组">
                <el-option label="普通用户" value="普通用户"></el-option>
                <el-option label="超级管理员" value="超级管理员"></el-option>
                </el-select>
            </el-form-item>
            
            <!-- 按钮 -->
            <el-form-item>
                <el-button type="primary" @click="add">添加</el-button>
                <el-button @click="reset">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
import {userAdd, userRepeat} from "@/api/user.js";  //引入账号管理模块接口
export default {
    data() {
        // 自定义账号验证
        let checkUser =async (rule, value, callback) => {
            if(value.length < 3){
                callback(new Error("账号必须3位数以上"));
            }else{
                let res = await userRepeat({account: value});
                if(res.data.code === 201){
                    callback(new Error(res.data.msg));
                }else{
                    callback();
                }
            }
        }
    return {
        form: {
            account: '',
            password: '',
            userGroup: "",
        },

        // 表单验证
        rules: {
            account: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                    { validator: checkUser, trigger: 'blur' },
                ],
            password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, message: '长度在6位数以上密码', trigger: 'blur' },
                ],
            userGroup: [
                    { required: true, message: '请选择用户组', trigger: 'blur' },
                ],
            }
        }
    },

    methods: {
        // 点击添加账号
        add() {
            this.$refs.form.validate(async (valid) => {
                if(valid){
                    await userAdd(this.form);
                    this.$router.push("/account/list");
                }else{
                    this.$message.error("添加失败");
                }
            });
        },
        // 点击重置
        reset(form) {
            this.$refs.form.resetFields();
        }
    }
}
</script>

<style lang="less" scoped>
.el-form{
    width: 300px;
}
</style>